package com.example.famhealing.init;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;

import com.example.famhealing.R;
import com.example.famhealing.util.Configuration;

public class AuthCodeActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_auth_code);
	}

	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.ok:
			if (checkAuthcode()) {
				Bundle extras = getIntent().getExtras();
				registerUser(extras);
			}
			intent = new Intent(this, IntroduceActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
			break;
		case R.id.menubtn:
			intent = new Intent(this, AuthCodeActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.auth_code, menu);
		return true;
	}

	private boolean checkAuthcode() {
		// not implemented
		return true;
	}

	private void registerUser(Bundle extras) {
		int exist = Configuration.getExist();
		String urlString = Configuration.FamhealingServerURL + "setUser.set";
		URL url;

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.permitNetwork().build());
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e) {
			throw new IllegalArgumentException("invalid url: " + urlString);
		}

		Map<String, String> params = (Map<String, String>) getIntent()
				.getSerializableExtra("map");
		StringBuilder bodyBuilder = new StringBuilder();
		Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, String> param = iterator.next();
			bodyBuilder.append(param.getKey()).append('=')
					.append(param.getValue());
			if (iterator.hasNext()) {
				bodyBuilder.append('&');
			}
		}
		bodyBuilder.append("&").append("invite=");
		switch (exist) {
		case 0:
			// constructs the POST body using the parameters
			bodyBuilder.append(0);
			break;
		case 1:
			bodyBuilder.append(1);
			break;
		}
		String body = bodyBuilder.toString();
		Log.v("[Debug]", "Posting '" + body + "' to " + url);
		byte[] bytes = body.getBytes();
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setFixedLengthStreamingMode(bytes.length);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded;charset=UTF-8");
			// post the request
			OutputStream out = conn.getOutputStream();
			out.write(bytes);
			out.close();
			// handle the response
			int status = conn.getResponseCode();
			if (status != 200) {
				throw new IOException("Post failed with error code " + status);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}
}
